import * as vscode from 'vscode'
import RecordViewProvider from './providers/recordViewProvider'
import { RecordService } from './services/recordService'
import { CommentService } from './services/commentService'
import { DetailPanelService } from './services/detailPanelService'
import { RecordCommands } from './commands/recordCommands'
import { EditCommands } from './commands/editCommands'
import { CodeLensProvider } from './providers/codeLensProvider'
import { RecordData } from './types'
import { COMMANDS } from './constants/commands'

// 打开记录引用位置的函数
function openRecordReference(item: RecordData) {
  const [start, end] = item.lineRange.split('-').map(Number)

  vscode.workspace.openTextDocument(item.filePath).then(doc => {
    vscode.window.showTextDocument(doc).then(editor => {
      const range = new vscode.Range(new vscode.Position(start - 1, 0), new vscode.Position(end - 1, 0))
      editor.revealRange(range, vscode.TextEditorRevealType.InCenter)
      editor.selection = new vscode.Selection(range.start, range.end)
    })
  })
}

export async function activate(context: vscode.ExtensionContext) {
  console.log('CodeMemo 插件激活')

  // 初始化服务
  const recordService = new RecordService(context)
  const commentService = new CommentService()

  // 读取配置
  const config = vscode.workspace.getConfiguration('codememo')
  const clearPanelsOnStartup = config.get('clearPanelsOnStartup', true)
  const allowMultipleDetailPanels = config.get('allowMultipleDetailPanels', false)

  // DetailPanelService 传入配置参数
  const detailPanelService = new DetailPanelService(
    (recordId: number) => recordService.findRecord(recordId),
    clearPanelsOnStartup,
    allowMultipleDetailPanels
  )

  console.log('=== CodeMemo 配置信息 ===')
  console.log(`启动时清理面板: ${clearPanelsOnStartup}`)
  console.log(`详情面板模式: ${allowMultipleDetailPanels ? '多开模式' : '单开模式'}`)
  console.log('========================')

  // 监听配置变化
  context.subscriptions.push(
    vscode.workspace.onDidChangeConfiguration(e => {
      if (e.affectsConfiguration('codememo.allowMultipleDetailPanels')) {
        const newAllowMultiple = vscode.workspace.getConfiguration('codememo').get('allowMultipleDetailPanels', false)
        console.log(`检测到面板模式配置变化: ${newAllowMultiple ? '多开' : '单开'}`)
        detailPanelService.updateConfig(newAllowMultiple)
      }
    })
  )

  // 数据迁移
  recordService.migrateRecordsData()

  // 注册WebView序列化器 - 处理重启后的恢复
  context.subscriptions.push(
    vscode.window.registerWebviewPanelSerializer('recordDetail', {
      async deserializeWebviewPanel(webviewPanel: vscode.WebviewPanel, state: any) {
        detailPanelService.deserializeDetailPanel(webviewPanel, state)
      }
    })
  )

  // 创建视图提供者
  const recordViewProvider = new RecordViewProvider(context.extensionUri, context)

  // 确保在插件停用时清理资源
  context.subscriptions.push(recordViewProvider)

  // 初始化命令处理器
  const recordCommands = new RecordCommands(context, recordService, commentService, detailPanelService, recordViewProvider)

  const editCommands = new EditCommands(recordService, commentService, recordViewProvider)

  // 注册视图
  context.subscriptions.push(vscode.window.registerWebviewViewProvider('codememo-records', recordViewProvider))

  // 注册CodeLens提供者
  const codeLensProvider = new CodeLensProvider(recordService)
  context.subscriptions.push(vscode.languages.registerCodeLensProvider('*', codeLensProvider))

  // 注册命令
  context.subscriptions.push(
    vscode.commands.registerCommand(COMMANDS.CREATE_RECORD, () => recordCommands.createRecordCommand()),
    vscode.commands.registerCommand(COMMANDS.OPEN_RECORD_VIEW, () => recordCommands.openRecordView()),
    vscode.commands.registerCommand(COMMANDS.OPEN_RECORD_REFERENCE, openRecordReference),
    vscode.commands.registerCommand(COMMANDS.UPDATE_RECORD_REFERENCE, (recordId: number) => recordCommands.updateRecordReference(recordId)),
    vscode.commands.registerCommand(COMMANDS.RECORD_DETAIL, (recordId: number) => recordCommands.recordDetail(recordId)),
    vscode.commands.registerCommand(COMMANDS.EDIT_RECORD, (recordId: number) => editCommands.editRecord(recordId)),
    vscode.commands.registerCommand(COMMANDS.DELETE_RECORD, (recordId: number) => recordCommands.deleteRecord(recordId)),
    vscode.commands.registerCommand(COMMANDS.GENERATE_COMMENT, (recordId: number) => recordCommands.generateComment(recordId)),
    vscode.commands.registerCommand(COMMANDS.REFRESH, () => {
      console.log('刷新记录列表')
      recordViewProvider.updateRecords(recordService.getWorkspaceRecords())
    })
  )

  // 更新视图数据
  recordViewProvider.updateRecords(recordService.getWorkspaceRecords())

  // 在插件激活时，检查是否存在未关闭的记录详情页

  console.log('CodeMemo 插件激活完成')
}
